import {
  PageContainer,
} from '@ant-design/pro-components';
import { useRequest, useModel } from '@umijs/max';
import { Button, Card, Input, Tree, message } from 'antd';
import type { TreeDataNode, TreeProps } from 'antd';
import type { FC } from 'react';
import { getMenuList, submitTask, getSubmitTask } from './service';
import React, { useEffect, useMemo, useState } from 'react';
import useStyles from './style.style';

const { Search } = Input;

const defaultData: TreeDataNode[] = [];

const dataList: { key: React.Key; title: string }[] = [];


const BasicForm: FC<Record<string, any>> = () => {
  const { styles } = useStyles();
  const { initialState } = useModel<any>('@@initialState');
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [selectMenu, setSelectMenu] = useState<any[]>([]);

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onSelect: TreeProps['onSelect'] = (selectedKeys) => {
    console.log('selected', selectedKeys, selectedKeys.join(','));
  };

  const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
    setSelectMenu(checkedKeys)
  };

  const getParentKey = (key: React.Key, tree: TreeDataNode[]): React.Key => {
    let parentKey: React.Key;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey!;
  };

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    const newExpandedKeys = dataList
      .map((item) => {
        if (item.title?.indexOf(value) > -1) {
          return getParentKey(item.key, defaultData);
        }
        return null;
      })
      .filter((item, i, self): item is React.Key => !!(item && self?.indexOf(item) === i));
    setExpandedKeys(newExpandedKeys);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  const { data: menuData } = useRequest(() => {
    return getMenuList(initialState?.currentUser?.merchant_id);
  });

  const generateList = (data: TreeDataNode[]) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key } = node;
      dataList.push({ key, title: key as string });
      if (node.children) {
        generateList(node.children);
      }
    }
  };

  const generateData = (menus: any) => {
    let dataTree: any = []
    if (menus?.menu) {
      Object.entries(menus.menu).forEach(([key, value]) => {
        dataTree.push({
          key,
          title: key,
          children: value.map((item: any) => ({
            key: item,
            title: item,
          }))
        });
      })
    }
    generateList(dataTree);
    return dataTree
  }
  const treeData = useMemo(() => {
    const loop = (data: TreeDataNode[]): TreeDataNode[] =>
      data.map((item) => {
        const strTitle = item.title as string;
        const index = strTitle?.indexOf(searchValue);
        const beforeStr = strTitle?.substring(0, index);
        const afterStr = strTitle?.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span key={item.key}>
              {beforeStr}
              <span className="site-tree-search-value">{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span key={item.key}>{strTitle}</span>
          );
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) };
        }

        return {
          title,
          key: item.key,
        };
      });
    if (!menuData) {
      return []
    }
    const data = generateData(menuData)
    return loop(data);
  }, [searchValue, menuData]);

  const { data: taskData, run: runTask, cancel } = useRequest(getSubmitTask, {
    manual: true,
    pollingInterval: 5000,
    pollingWhenHidden: false,
  });

  const { run } = useRequest(submitTask, {
    manual: true,
    onSuccess: (data) => {
      runTask(data.id)
      message.success('提交成功');
    },
  });

  const createEvaluate = () => {
    run({ merchant_id: initialState?.currentUser?.merchant_id, data: selectMenu })
  }

  useEffect(() => {
    console.log(11, taskData)
    if (taskData?.comment?.content) {
      cancel?.()
    }
  }, [taskData?.comment?.content])

  return (
    <PageContainer content='服务端首页' style={{
      height: '100vh',
      background: 'linear-gradient(#ffffff, #f5f5f5 28%)',
      overflow: 'auto',
    }}>
      <div className={styles.edit_wrap}>
        <Card bordered={false} className={styles.edit_wrap_left}>
          <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={onChange} />
          <Tree
            checkable
            onSelect={onSelect}
            onCheck={onCheck}
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            treeData={treeData}
          />
          <Button onClick={createEvaluate} style={{ marginTop: 24 }}>生成评价内容</Button>
        </Card>
        <Card bordered={false} className={styles.edit_wrap_right}>
          <div>评价内容</div>
          <div>
            <div>{taskData?.comment?.content || ''}</div>
            {taskData?.comment?.content && <Button onClick={createEvaluate} style={{ marginTop: 24 }}>不满意？重新生成</Button>}
          </div>
        </Card>
      </div>
    </PageContainer>
  );
};
export default BasicForm;
